import os
import sys
import logging
from pathlib import Path
from PySide6.QtWidgets import QApplication
from app.gui.main_window import MainWindow
from app.models.db import DBConnection

# 添加项目根目录到 Python 路径
project_root = Path(__file__).parent
sys.path.insert(0, str(project_root))

# 配置日志
logging.basicConfig(
    level=logging.INFO,
    format='%(asctime)s [%(levelname)s] %(message)s',
    handlers=[
        logging.StreamHandler(),
        logging.FileHandler('app.log', encoding='utf-8')
    ]
)

logger = logging.getLogger(__name__)

def main():
    try:
        # 初始化数据库连接池
        logger.info("正在初始化数据库连接池...")
        DBConnection.init_pool()
        
        # 创建应用
        app = QApplication(sys.argv)
        
        # 创建并显示主窗口
        window = MainWindow()
        window.show()
        
        # 运行应用
        sys.exit(app.exec())
        
    except Exception as e:
        logger.error(f"程序启动失败: {e}", exc_info=True)
        sys.exit(1)
    finally:
        # 确保程序退出时关闭数据库连接池
        if hasattr(DBConnection, '_pool') and DBConnection._pool:
            DBConnection._pool.close()
            logger.info("数据库连接池已关闭")

if __name__ == '__main__':
    main() 